import request from '@/utils/request_vistor';

const VITE_API_USER_NAME = import.meta.env.VITE_API_VISTOR_USER_NAME;
const VITE_API_USER_PASSWORD = import.meta.env.VITE_API_VISTOR_USER_PASSWORD;


/* 
 获取访客登录 token, 获取成功 并缓存访客 Token
  vistorToken: string
*/
export async function getVisitorToken() {
  //  无需 token
  const res: any = await request({
    url: '/login',
    method: 'post',
    data: {
      "username": VITE_API_USER_NAME,
      "password": VITE_API_USER_PASSWORD,
    }
  })

  const { code, token } = res;

  if (code !== 200) {
    return Promise.reject(new Error('获取访客登录 token 失败'))
  }

  //  缓存访客 Token - 共后面接口再次调用
  localStorage.setItem('vistorToken', token);
}

/* 
  获取访客数据
  visitorData: IObject
*/
export async function getVisitorData() {
  //  判断是否存在token
  if (!localStorage.getItem('vistorToken')) {
    await getVisitorToken();
  }

  const res: any = await request({
    url: '/statistics/info/visit',
    method: 'get'
  })

  const { code } = res;
  //  数据异常 - 重新请求数据
  if (code === 401) {
    localStorage.removeItem('vistorToken');
    return getVisitorData();
  }

  return res;
}


/* 
  获取今日访客列表数据
  visitorData: IObject
*/
export async function getTodayVisitorList(data: any = { pageNum: 1, pageSize: 10000 }) {
  //  判断是否存在token
  if (!localStorage.getItem('vistorToken')) {
    await getVisitorToken();
  }

  const res: any = await request({
    url: '/statistics/info/todayVisitorList',
    method: 'get',
    params: data
  })

  const { code } = res;
  //  数据异常 - 重新请求数据
  if (code === 401) {
    localStorage.removeItem('vistorToken');
    return getTodayVisitorList();
  }

  return res;
}